home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: news.sprintlink.net!news1!news
- From: rclark@iquest.net (Robert B. Clark)
- Subject: Re: Ability to locate spaces?
- X-Nntp-Posting-Host: ind-004-236-169.iquest.net
- Message-ID: <3129dc3a.706665@news.iquest.net>
- Sender: news@iquest.net (News Admin)
- Organization: IQuest Internet, Inc.
- X-Newsreader: Forte Agent .99d/16.182
- References: <Pine.SOL.3.91.960215222301.15979A-100000@teer1.acpub.duke.edu>
- Date: Tue, 20 Feb 1996 15:45:03 GMT
-
- On Thu, 15 Feb 1996 22:30:23 -0500, John Young Oh <jyo@acpub.duke.edu>
- wrote:
-
- >I am trying to write a program that reads an input file and locates where
- >the spaces are located. For example, if a line from the input file read:
- >555555.55 5555.55 5555.55
- >
- >I would like the program to be able to recognize that there are spaces
- >between the numbers and keep track of them. What I did was to use
- >fgets and read in the line into a string. I then used a for loop
- >and checked each array element of the character string and used an
- >if statement to see if an array element was a space.
- >Here are the lines of code:
- >
- >FILE *input;
- >char *string, buf[200];
- >int i, count;
- >input = fopen ("data", "r");
- >(etc etc etc)
- >string = fgets (buf, 199, input);
- >for (i = 0; i < 40; ++i)
- >{
- > if (buf[i] == ' ')
- > {
- > ++count;
- > }
- >}
- >
- >What is wrong with this code? It does not seem to work.
-
- Pretty vague. What sort of errors are you getting?
-
- Is 'count' not correct? If not, do you initialize 'count' to zero in
- the "etc etc etc" code?
-
- Is the data file "data" correct? Does it exist?
-
- Are you actually getting anything from the fgets() call? Your code
- doesn't check for read errors, so if the file were empty you'd never
- know it.
-
- I don't know if you want to keep track of the offsets of the spaces (per
- your text in the first paragraph) or simply count the number of spaces
- (per your code). For the latter, why not simply use strchr()
- recursively:
-
- /* count.c - Recursively count spaces in string. Turbo C v3.0
- Written 19 Feb 1996 by Robert B. Clark <rclark@iquest.net>
- Donated to the public domain. */
-
- #include <stdio.h>
- #include <string.h> /* For strchr() function */
-
- int count_spaces(const char *s)
- {
- static int count;
- char *p;
-
- if ((p=strchr(s,' '))!=NULL) { /* Find next space character */
- count++; /* Increment counter */
- count_spaces(p+1); /* Go back for more */
- }
- return count;
- }
-
-
- int main(int argc, char *argv[])
- {
- char str[50]="This string contains four spaces.";
- int x;
-
- if (argc>1) strcpy(str,argv[1]);
- x=count_spaces(str);
- printf("\n\"%s\" has %d ASCII 0x20 chars.",str,x);
- return x;
- }
-
- --
- Robert B. Clark <rclark@iquest.net>
- "Be wary of strong spirits. It can make you shoot at tax collectors...
- and miss." --RAH
-